package com.feeyin.radar.commons;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Properties;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.multipart.MultipartFile;

public class FileUtils
{
  private static String dataBaseName = "rone";
  private static String hostName = "localhost";
  private static String userName = "root";
  private static String passWord = "000000";
  private static String mysqlHomePath = "C:\\Program Files\\MySQL\\MySQL Server 5.1\\bin;";

  private static Properties properties = new Properties();

  static {
    InputStream inputStream = FileUtils.class.getClassLoader().getResourceAsStream("config/jdbc.properties");
    try {
      properties.load(inputStream);
      dataBaseName = properties.getProperty("jdbc.databasename");
      hostName = properties.getProperty("jdbc.hostname");
      userName = properties.getProperty("jdbc.username");
      passWord = properties.getProperty("jdbc.password");
      mysqlHomePath = properties.getProperty("jdbc.mysqlhomepath");
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public static boolean saveFile(String storedPath, MultipartFile multipartFile)
  {
    try
    {
      FileOutputStream fileOutputStream = new FileOutputStream(storedPath);
      byte[] buffer = new byte[1048576];
      int byteSum = 0;
      int byteRead = 0;
      InputStream stream = multipartFile.getInputStream();

      while ((byteRead = stream.read(buffer)) != -1) {
        byteSum += byteRead;
        fileOutputStream.write(buffer, 0, byteRead);
        fileOutputStream.flush();
      }
      fileOutputStream.close();
      stream.close();
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
    FileOutputStream fileOutputStream;
    return true;
  }

  public void downloadCustomerTemplate(String realPath, HttpServletResponse response, int sign)
  {
    String basePath = realPath + "upload" + System.getProperty("file.separator") + "template";
    String storedPath = "";
    if (sign == 2)
      storedPath = basePath + System.getProperty("file.separator") + "marketingCustomer.xls";
    else if (sign == 3)
      storedPath = basePath + System.getProperty("file.separator") + "contract.xls";
    else if (sign == 11)
      storedPath = basePath + System.getProperty("file.separator") + "linkman.xls";
    else {
      storedPath = basePath + System.getProperty("file.separator") + "customer.xls";
    }

    String path = storedPath;
    try {
      File file = new File(path);
      String filename = file.getName();
      String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

      InputStream fis = new BufferedInputStream(new FileInputStream(path));
      byte[] buffer = new byte[fis.available()];
      fis.read(buffer);
      fis.close();
      response.reset();

      response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
      response.addHeader("Content-Length", file.length()+"");
      OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
      response.setContentType("application/octet-stream");
      toClient.write(buffer);
      toClient.flush();
      toClient.close();
    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }

  public static String[] createExcuteBackUpBatFile(String realPath, String sign)
    throws Exception
  {
    if (StringUtils.isEmpty(realPath)) return null;
    if (StringUtils.isEmpty(sign)) return null;

    String[] array = new String[3];
    Date date = new Date();
    String year = DateUtils.getStringDateByFormat(date, "yyyy");
    String month = DateUtils.getStringDateByFormat(date, "MM");
    String backupPath = realPath + "backup" + System.getProperty("file.separator") + 
      year + System.getProperty("file.separator") + month + System.getProperty("file.separator");

    File file = new File(backupPath);
    if ((!file.exists()) || (!file.isDirectory()))
    {
      file.mkdirs();
    }

    String batPath = realPath + "WEB-INF\\classes\\config\\batfile\\backup_database.bat";

    File batFile = new File(batPath);

    String curSysDate = DateUtils.getStringDateByFormat(new Date(), "yyyyMMddHHmmss");
    String backupName = sign + dataBaseName + curSysDate + ".sql";
    FileWriter fileWriter = new FileWriter(batFile, false);
    BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
    StringBuffer actionString = new StringBuffer();
    actionString.append("set path=" + mysqlHomePath + "%path%");
    actionString.append("\n");
    actionString.append("cd " + backupPath);
    actionString.append("\n");
    actionString.append(backupPath.substring(0, 2));
    actionString.append("\n");
    actionString.append("mysqldump -h " + hostName + " -u" + userName + " -p" + passWord + " " + dataBaseName + " > " + backupName);
    actionString.append("\n");
    actionString.append("exit");

    fileWriter.write(actionString.toString());
    fileWriter.flush();
    fileWriter.close();
    bufferedWriter.close();

    Runtime rt = Runtime.getRuntime();
    Process ps = null;
    ps = rt.exec("cmd.exe /c start " + batPath);
    ps.waitFor();
    int i = ps.exitValue();
    if (i == 0)
    {
      array[0] = DateUtils.getStringDateByFormat(date, "yyyy-MM-dd HH:mm:ss");
      array[1] = backupName;
      array[2] = backupPath;
      Thread.sleep(5000L);
    }
    return array;
  }

  public static boolean createRestoreBackUpBatFile(String realPath, String allPath)
    throws Exception
  {
    if (StringUtils.isEmpty(realPath)) return false;
    if (StringUtils.isEmpty(allPath)) return false;

    File file = new File(allPath);
    if ((!file.exists()) || (!file.isFile())) return false;
    String restoreFileName = file.getName();
    if (StringUtils.isEmpty(restoreFileName)) return false;

    String batPath = realPath + "WEB-INF\\classes\\config\\batfile\\restore_database.bat";
    File batFile = new File(batPath);

    String restorePath = allPath.substring(0, allPath.indexOf(restoreFileName));
    FileWriter fileWriter = new FileWriter(batFile, false);
    StringBuffer cmdStr = new StringBuffer();
    cmdStr.append("set path=" + mysqlHomePath + "%path%");
    cmdStr.append("\n");
    cmdStr.append("cd " + restorePath);
    cmdStr.append("\n");
    cmdStr.append(restorePath.substring(0, 2));
    cmdStr.append("\n");

    cmdStr.append("mysql -u" + userName + " -p" + passWord + " " + dataBaseName + "<" + restoreFileName);
    cmdStr.append("\n");
    cmdStr.append("exit");

    fileWriter.write(cmdStr.toString());
    fileWriter.flush();
    fileWriter.close();

    Runtime rt = Runtime.getRuntime();
    Process ps = null;
    ps = rt.exec("cmd.exe /c start " + batPath);
    ps.waitFor();
    int i = ps.exitValue();
    if (i == 0) {
      Thread.sleep(5000L);
      return true;
    }
    return false;
  }

  public static void main(String[] args)
  {
  }
}